package com.smforj.ssm.modules.sys.util;

import java.sql.PreparedStatement;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.smforj.ssm.frame.core.dao.DbPoolConnection;
import com.smforj.ssm.frame.core.utils.SpringContextHolder;
import com.smforj.ssm.mina.codec.MsgEntity;
import com.smforj.ssm.mina.message.MessageModel;
import com.smforj.ssm.mina.server.R;
import com.smforj.ssm.mina.service.TsFaceService;
import com.smforj.ssm.mina.util.ThreadPool;

public class Sip2MinaServerHandler extends IoHandlerAdapter {

       private Logger logger = Logger.getLogger("Sip2MinaServerHandler");
	  
	  @Override
		public void sessionCreated(IoSession session) throws Exception {
			logger.debug("Server"+this.getClass().getName() + "连接创建 : " + session.getRemoteAddress()
					+ "  sessionId=" + session.getId());
		}

		// 当一个客户端连接进入时
		@Override
		public void sessionOpened(IoSession session) throws Exception {
			logger.debug("Server"+this.getClass().getName() + "连接打开 : " + session.getRemoteAddress()
					+ "  sessionId=" + session.getId());
		}

		// 当一个客户端连接关闭时
		@Override
		public void sessionClosed(IoSession session) {
			logger.debug("Server"+this.getClass().getName() + "连接关闭 : " + session.getRemoteAddress()
					+ "  sessionId=" + session.getId());
		}

		@Override
		public void sessionIdle(IoSession session, IdleStatus status)
				throws Exception {
			logger.debug("Server"+this.getClass().getName() + "连接空闲 : " + session.getRemoteAddress() + "  sessionId=" + session.getId());
			//session.close();
			session.close(true);
		}

		@Override
		public void messageSent(IoSession session, Object message) throws Exception {
			logger.debug("Server"+String.format("向Server[%s]发送消息:%s",
					session.getRemoteAddress(), message.toString()));
		}

		@Override
		public void messageReceived(IoSession session, Object message)
				throws Exception {
			logger.debug("Server "+this.getClass().getName() +" messageReceived");
			// ---------------- 接收响应 开始 ---------------------
			// 使用解码器后，message对象就是数据实体对象了，直接强转
			String reqME = message.toString();
			logger.debug("messageReceived: "+reqME); 
			
			
/*			String sql = "select count(jszh) from [dbo].[t_dz_table]";
			DbPoolConnection dbp = (DbPoolConnection)SpringContextHolder.getBean("dbPoolConnection"); 
	        DruidPooledConnection con = dbp.getConnection();  
	        PreparedStatement ps = con.prepareStatement(sql);  
	        Boolean i = ps.execute();  
			logger.debug("executeUpdate: "+i); 
	        ps.close();  
	        con.close();  
	        dbp = null; */ 
			/*
			//显示消息头信息
			byte[] dest = new byte[180];
			byte[] src = MsgUtils.stringToBytes(reqME);
			System.arraycopy(src, 0, dest, 0, dest.length);
			logger.debug(String.format("收到 终端 [%s] 数据:%s",session.getRemoteAddress(), ComHex.bytesToString(dest)));
			*/
			/*
			 * 输出结果到GUI面板中
			 */
			//String dataTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(new Date());
			//DataReceiveFrame.setTextArea(dataTime+"收到 终端:"+session.getRemoteAddress()+"数据:");
			//将消息头写上UI
			//DataReceiveFrame.setTextArea(ComHex.bytesToString(dest).toString());
			// ---------------- 接收响应 结束 ---------------------
			// ---------------- 业务处理 开始 ---------------------
	/*		Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
			System.out.println(reqME);
			System.err.println("当前线程数：" + map.size());*/
			//----------------  ----------------
			//根据消息标识判断业务处理 
			// ---------------- 业务处理 结束 ---------------------
			//发送消息打印
			/*
			//获取所有连接
			Collection<IoSession> sessions = session.getService().getManagedSessions().values();
			for(IoSession is : sessions)
			{
				is.getLocalAddress();
			}
			*/
			// ---------------- 发送响应 开始 ---------------------
			// 将消息返回给客户端，信息头四位是表示长度的二进制数，后边是true或false的字符串
			// 创建一个返回数据用的实体对象 
			session.write(new MsgEntity(R.SUCCESSED)); 
			// ---------------- 发送响应 结束 --------------------- 
		}
		
		  //创建线程（并发）池，自动伸缩(自动条件线程池大小)
	    //ExecutorService es =  Executors.newCachedThreadPool(new WorkThreadFactory());
		private void saveOrUpdateMsg(MessageModel model) { 
	        //工作线程
			ThreadPool.es.execute(new TsFaceService(model)); 
	        //指示当所有线程执行完毕后关闭线程池和工作线程，如果不调用此方法，jvm不会自动关闭
			//ThreadPool.es.shutdown();   
		} 

		@Override
		public void exceptionCaught(IoSession session, Throwable cause)
				throws Exception {
			logger.debug(this.getClass().getName() + "终端产生异常 : " +cause.getMessage()+ session.getRemoteAddress()
					+ "  sessionId=" + session.getId());
			session.close(true);
		}
}
